package chat.service;


import chat.UserDto.LogChatDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import top.revery.api.entity.chat.BaseLogChat;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Map;

/**
 * @author denghao
 * @title
 * @package
 * @date 2020/1/6 9:35
 */

@Service
public class LogChatService {
    @Autowired
    private LogChatDto logChatDto;

    public Page<BaseLogChat> getList(int pageNum, int pageSize, Map map) {


        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "addTime");
        Specification<BaseLogChat> specification = createSpecification(map);
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize,Sort.by(order));
        return logChatDto.findAll(specification, pageRequest);

    }

    private Specification<BaseLogChat> createSpecification(Map map) {


        return new Specification<BaseLogChat>() {
            @Override
            public Predicate toPredicate(Root<BaseLogChat> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                if (map.get("From_Account") != null && !"".equals(map.get("From_Account"))) {
                    predicate.getExpressions().add(cb.equal(root.get("From_Account"), map.get("From_Account")));
                }

                if (map.get("To_Account") != null && !"".equals(map.get("To_Account"))) {
                    predicate.getExpressions().add(cb.equal(root.get("To_Account"), map.get("To_Account")));
                }
                //发布日期查询
                if (map.get("startTime") != null && !"".equals(map.get("startTime"))) {
                    predicate.getExpressions().add(cb.greaterThanOrEqualTo(root.get("addTime").as(String.class), (String) map.get("startTime")));
                }
                if (map.get("endTime") != null && !"".equals(map.get("endTime"))) {
                    predicate.getExpressions().add(cb.lessThanOrEqualTo(root.get("addTime").as(String.class), (String) map.get("endTime")));
                }
                return predicate;
            }
        };
    }
}
